﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using Emz.Core.Base;
using Emz.Core.Repositories;
using Emz.Core.Models;
using Legazpi.Payroll.Services.Interfaces;

namespace Legazpi.Payroll.Services.Services
{
    public class SettingsService : ISettingsService
    {
        #region Fields

        private DbContext _dbContext;
        private ISettingsRepository _settingsRepository;
        private IDatabaseFactory _dbFactory;

        #endregion

        #region ctor

        public SettingsService()
            : this(new DatabaseFactory())
        {

        }

        public SettingsService(IDatabaseFactory dbFactory)
        {
            if (dbFactory == null) throw new ArgumentNullException("dbFactory");
            _dbFactory = dbFactory;
            DbContext = dbFactory.Get();
        }

        private DbContext DbContext
        {
            get { return _dbContext; }
            set
            {
                _dbContext = value;
                _settingsRepository = new SettingsRepository(_dbContext);
            }
        }

        #endregion


        public Settings GetBySettingName(string settingName)
        {
            return _settingsRepository.Get(x => x.SettingName == settingName);
        }
        
        public string GetValueBySettingName(string settingName)
        {
            var setting = GetBySettingName(settingName);
            return setting != null ? setting.SettingValue : "";
        }

        public void Update(Settings setting)
        {
            _settingsRepository.Update(setting);
        }

        public bool Save()
        {
            string message;
            _settingsRepository.Save(out message);
            return message == "Saved";
        }

    }
}
